package com.aliang.frame.controller.admin;

import com.aliang.frame.base.BaseApiController;
import com.aliang.frame.base.RestResponse;
import com.aliang.frame.domain.Dept;
import com.aliang.frame.domain.User;
import com.aliang.frame.service.DeptService;
import com.aliang.frame.viewmodel.admin.dept.DeptAndChirdResponseVM;
import com.aliang.frame.viewmodel.admin.dept.DeptPageRequestVM;
import com.aliang.frame.viewmodel.admin.dept.DeptPageResponseVM;
import com.aliang.frame.viewmodel.admin.dept.DeptRequestVM;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 部门管理
 */
@RestController("DeptController")
@RequestMapping(value = "/api/admin/dept")
public class DeptController extends BaseApiController {

    private final DeptService deptService;

    public DeptController(DeptService deptService) {
        this.deptService = deptService;
    }


    /**
     * 获取部门列表
     * @param model
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<List<DeptAndChirdResponseVM>> pageList(@RequestBody DeptPageRequestVM model) {
        List<DeptAndChirdResponseVM> resultList = new ArrayList<>();

        User currentUser = getCurrentUser();
        model.setDeptId(currentUser.getDeptId());
        List<Dept> deptList = deptService.page(model);
        List<DeptAndChirdResponseVM> vmlist = deptList.stream()
                .map(t -> modelMapper.map(t, DeptAndChirdResponseVM.class)).collect(Collectors.toList());

        Map<Integer, DeptAndChirdResponseVM> tempMap = vmlist.stream()
                .collect(Collectors.toMap(DeptAndChirdResponseVM::getId, v -> v, (oldKey, newKey) -> newKey));

        vmlist.stream().forEach(item -> {

            if (item.getParentId() == null || item.getId() == currentUser.getDeptId()) {
                resultList.add(item);//如果父节点为null，表命一级部门，直接录入
            }

            //获取父节点
            DeptAndChirdResponseVM vm = tempMap.get(item.getParentId());
            if (null != vm) {
                if (null == vm.getChirds()) {
                    vm.setChirds(new ArrayList<>());
                }
                vm.getChirds().add(item);
            }
        });
        return RestResponse.ok(resultList);
    }

    /**
     * 编辑部门信息
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid DeptRequestVM model) {
        if (model.getId() != null && model.getId() == model.getParentId()) {
            return RestResponse.fail(501, "上级部门不能是当前部门");
        }
        deptService.edit(model, getCurrentUser());
        DeptPageResponseVM vm = deptService.deptToVM(model.getId());
        return RestResponse.ok(vm);
    }

    /**
     * 查询部门信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<DeptPageResponseVM> select(@PathVariable Integer id) {
        DeptPageResponseVM vm = deptService.deptToVM(id);
        return RestResponse.ok(vm);
    }

    /**
     * 删除部门
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        Dept dept = deptService.selectById(id);
        dept.setDeleted(true);  // 标记为删除
        deptService.updateByIdFilter(dept);
        return RestResponse.ok();
    }

    /**
     * 修改部门状态
     * @param id
     * @return
     */
    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Boolean> changeStatus(@PathVariable Integer id) {
        Dept dept = deptService.selectById(id);
        dept.setStatus(!dept.getStatus());
        dept.setUpdateTime(new Date());
        dept.setUpdateBy(getCurrentUser().getId());
        deptService.updateByIdFilter(dept);
        return RestResponse.ok(dept.getStatus());
    }

    /**
     * 获取部门列表
     * @return
     */
    @RequestMapping(value = "/select", method = RequestMethod.POST)
    public RestResponse<List<DeptAndChirdResponseVM>> selectByCurrentUser() {
        List<DeptAndChirdResponseVM> resultList = new ArrayList<>();

        User currentUser = getCurrentUser();
        List<Dept> deptList = deptService.selectByCurrentUser(currentUser.getDeptId());
        List<DeptAndChirdResponseVM> vmlist = deptList.stream()
                .map(t -> modelMapper.map(t, DeptAndChirdResponseVM.class)).collect(Collectors.toList());

        Map<Integer, DeptAndChirdResponseVM> tempMap = vmlist.stream()
                .collect(Collectors.toMap(DeptAndChirdResponseVM::getId, v -> v, (oldKey, newKey) -> newKey));

        vmlist.stream().forEach(item -> {
            if (item.getParentId() == null || item.getId() == currentUser.getDeptId()) {
                resultList.add(item);//如果父节点为null，表命一级部门，直接录入
            }
            //获取父节点
            DeptAndChirdResponseVM vm = tempMap.get(item.getParentId());
            if (null != vm) {
                if (null == vm.getChirds()) {
                    vm.setChirds(new ArrayList<>());
                }
                vm.getChirds().add(item);
            }
        });
        return RestResponse.ok(resultList);
    }

}
